<?php
namespace app\pays;

use pqphp\base\Model;
/**
 * 所有支付接口，包含微信、支付宝和第三方 2018-3-7 温宗敏
 */
class CustomCommon
{

	protected $config=[];//读取config配置文件

	// 构造函数，初始化属性，并实例化对应模型
    public function __construct()
    {
		$this->config = include("../pays/config/config.php");
    }


	/*数据处理，返回json数据格式
	 */
	function errormsg($msg)
	{
		$this->paylogs($msg);
		exit(json_encode(array('code'=>-1, 'message'=>$msg)));
	}

	/*日志记录处理
	 */
	function paylogs($msg)
	{
		$logModel = new Model();
		$logModel->paylogs($msg);
	}

	function ToXml($input)
    {
        if(empty($input)
            || count($input) <= 0)
        {
            $this->paylogs('数组数据异常');
        }
        $xml = "<xml>";
        foreach ($input as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

	function toArray($xml)  
    {  
        //将XML转为array,禁止引用外部xml实体  
        libxml_disable_entity_loader(true);  
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);  
    }  

	/**
	 * 
	 * 拼接签名字符串
	 * @param array $urlObj
	 * 
	 * @return 返回已经拼接好的字符串
	 */
	function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			if($k != "sign"){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}

	/**
	 * GET 或者POST 请求
	 * 
	 * @return openid
	 */
	public function RequestUrl($url,$type,$post_data=null)
	{
		//初始化curl
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		if(strtolower($type)=="post")
		{
			//设置post方式提交
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//运行curl，结果以json形式返回
		$res = curl_exec($ch);
		$error = curl_error($ch);
		if ($error){
			$this->errormsg($type.'请求发生错误'.$error);
		}
		// 获得响应结果里的：头大小  
		$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);  
		// 根据头大小去获取头信息内容  
		$content = substr($res, $headerSize); 
		curl_close($ch);
		return json_decode($content,true);
	}
}